package com.hqj.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.hqj.entity.TUser;
import com.hqj.service.TUserServiceImpl;
import com.hqj.util.AccountUtil;
import com.hqj.util.ReturnValueUtil;
import com.hqj.util.SendMsgUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hqj
 * @since 2020-06-10
 */
@Controller
@RequestMapping("/uc")
public class TUserController extends BaseController<TUser> {

    @Resource(name="TUserServiceImpl")
    private TUserServiceImpl tsi;

    @Override
    public String index() {
        return "admin/user/index";
    }

    @RequestMapping("/editPwd")
    public String editPwd(){
        return "admin/user/editPwd";
    }

    @Override
    public String addEdit(HttpServletRequest req, Model model) {
        String id = req.getParameter("id");
        if(id!=null){
            TUser tUser = tsi.getById(id);
            model.addAttribute("user",tUser);
            return "admin/user/edit";
        }
        return "admin/user/add";
    }

    @Override
    public String find(TUser tUser) {
        List<TUser> list = tsi.list(null);

        return ReturnValueUtil.findData(list.size(),list);
    }

    @Override
    public Map<String, Object> add(TUser tUser) {
        boolean b = tsi.save(tUser);
        return ReturnValueUtil.aer(b,"新增");
    }

    @Override
    public Map<String, Object> edit(TUser tUser) {
        boolean b = tsi.updateById(tUser);
        return ReturnValueUtil.aer(b,"编辑");
    }

    @Override
    public Map<String, Object> remove(TUser tUser) {
        boolean b = tsi.removeById(tUser.getId());
        return ReturnValueUtil.aer(b,"删除");
    }

    @RequestMapping("/toLogin")
    @ResponseBody
    public Map<String,Object> toLogin(@Param("account") String account
            , @Param("password") String password, @Param("code") String code){
        Map map = new HashMap();
        Subject subject = SecurityUtils.getSubject();
        //TODO 验证登录验证码是否正确
        Session session = subject.getSession();
        String codeImg = session.getAttribute("loginCode")+"";
        //销毁session 验证码
        session.removeAttribute("loginCode");
        if(!(code!=null&&code.equalsIgnoreCase(codeImg))){
            map.put("msg","验证码错误!");
            map.put("is",false);
            return map;
        }
        //使用shiro对账号进行认证
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(account,password);
        //是否启用shiro认证
        usernamePasswordToken.setRememberMe(true);
        try {
            //执行认证 有异常说明登录失败，否则登录成功
            subject.login(usernamePasswordToken);
            //TODO 权限查询


            TUser t = tsi.getOne(new QueryWrapper<TUser>().eq(AccountUtil.getLoginType(account),account));
            t.setPassword("");//清除敏感信息
            session.setAttribute("user",t);//把内容存入会话
            map.put("msg","登录成功");
            map.put("is",true);
        }catch (UnknownAccountException e){//捕捉账号不存在的异常
            map.put("msg","账号不存在!");
            map.put("is",false);
        }catch (IncorrectCredentialsException e){//捕捉密码错误的异常
            map.put("msg","密码错误!");
            map.put("is",false);
        }catch (Exception e){
            e.printStackTrace();//堆栈  堆：先进先出  栈:后进先出
            //e.getMessage();
        }finally{

        }

        return map;
    }

    @RequestMapping("/sendSms")
    @ResponseBody
    public Map<String,Object> sendSms(@Param("mobile") String mobile){
        Map map = new HashMap();
        Random r = new Random();
        int i = r.nextInt(90)+10;//10-99

        String code = (r.nextInt(9000)+1000)+"";//1000-9999
        //TODO 把验证码添加到session

        boolean flat = SendMsgUtil.sendSms(mobile,"1",new String[]{code,"5"});
        map.put("msg","短信发送"+(flat?"成功":"失败"));
        return map;
    }
}
